#include "khttpmanager.h"
#include <qjsondocument.h>

KHttpManager::KHttpManager(QObject *parent)
	: QObject(parent)
{}

KHttpManager::~KHttpManager()
{}

void KHttpManager::httpGet(const QString & httpURL)
{
	m_netManager = new QNetworkAccessManager(this);
	QUrl requestURL(httpURL);
	QNetworkRequest request(requestURL);
	QNetworkReply* reply = m_netManager->get(request);
	connect(reply, &QNetworkReply::readyRead, this, &KHttpManager::onReadData);
	connect(reply, &QNetworkReply::finished, this, &KHttpManager::onHandleFinished);
	connect(reply, QOverload<QNetworkReply::NetworkError>::of(&QNetworkReply::error),
		this, &KHttpManager::onHandleHttpError);
}

void KHttpManager::httpDownload(const QString& fileURL, const QString& saveFileName)
{
	m_fileOutput.setFileName(saveFileName);
	if (!m_fileOutput.open(QIODevice::WriteOnly)) 
	{
		qDebug() << "openning save file:" << saveFileName << " error.";
		return;
	}

	m_netManager = new QNetworkAccessManager(this);
	QNetworkRequest request(fileURL);
	QNetworkReply* reply = m_netManager->get(request);
	connect(reply, &QNetworkReply::readyRead, this, &KHttpManager::onSaveData);
	connect(reply, &QNetworkReply::finished, this, &KHttpManager::downloadedFinished);
	connect(reply, &QNetworkReply::downloadProgress, this, &KHttpManager::downloadProgress);
}

void KHttpManager::onReadData()
{
	QNetworkReply* reply = (QNetworkReply*)this->sender();
	if (reply->error() == QNetworkReply::NoError)
		m_httpData += reply->readAll();
}

void KHttpManager::onSaveData()
{
	QNetworkReply* reply = (QNetworkReply*)this->sender();
	if (reply->error() == QNetworkReply::NoError)
		m_fileOutput.write(reply->readAll());
}

void KHttpManager::onHandleFinished()
{

	QNetworkReply* reply = (QNetworkReply*)this->sender();
	if (reply->error() == QNetworkReply::NoError)
		emit readyReadHttp(m_httpData,reply->url());

	m_httpData.clear();
	reply->deleteLater();
}

void KHttpManager::downloadedFinished()
{
	QNetworkReply* reply = (QNetworkReply*)this->sender();
	if (reply->error() == QNetworkReply::NoError)
		emit readyDownloadHttp();

	m_fileOutput.close();
	reply->deleteLater();
}

void KHttpManager::onHandleHttpError(QNetworkReply::NetworkError code)
{
	qDebug() << "network error:" << code;
}
